package com.example.demo.controller;

import com.example.demo.dao.TUserMapper;
import com.example.demo.model.TUser;
import com.example.demo.model.UserInfoDO;
import com.example.demo.service.UserService;
import com.gitee.fastmybatis.core.PageInfo;
import com.gitee.fastmybatis.core.query.Query;
import com.gitee.fastmybatis.core.util.MapperUtil;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;

import java.util.Arrays;
import java.util.List;

@Controller
public class UserController {

    @Inject
    private UserService userService;

    /**
     * http://localhost:6041/index
     *
     * @return
     */
    @Mapping("index")
    public TUser index() {
        joinPage();
        return userService.getById(6);
    }

    /**
     * http://localhost:6041/index2
     *
     * @return
     */
    @Mapping("index2")
    public List<TUser> index2() {
        Query query = Query.create()
                .in("id", Arrays.asList(4, 5, 6));
        return userService.list(query);
    }


    /**
     * 演示联表查询且分页
     */
    public static void joinPage() {
        TUserMapper tUserMapper = Solon.context().getBean(TUserMapper.class);

        Query query = Query.create()
                // 联表查询需要带上表别名t.
                .gt("t.`id`", 1)
                .eq("t2.`city`", "杭州")
                .page(1, 10);

        // 分页查询只需要返回总数，以及当前分页内容
        PageInfo<UserInfoDO> pageInfo = MapperUtil.query(query, tUserMapper::getUserInfoCount, tUserMapper::listUserInfo);

        List<UserInfoDO> list = pageInfo.getList(); // 结果集
        long total = pageInfo.getTotal(); // 总记录数
        int pageCount = pageInfo.getPageCount(); // 共几页

        System.out.println("total:" + total);
        System.out.println("pageCount:" + pageCount);
        list.forEach(System.out::println);

        // JPA findByXxx
        List<TUser> userList = tUserMapper.findByUsernameLike("张");
        userList.forEach(System.out::println);
    }

}
